package com.x.netty.netty.file;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @Author _G5niusX
 * @Date 2018/5/27 11:10
 */
public final class FileNettyServer {
    private final int port;

    public FileNettyServer(int port) {
        this.port = port;
    }

    public void accept() throws InterruptedException {
        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(eventLoopGroup, eventExecutors).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new FileServerHandler());
            }
        });
        ChannelFuture channelFuture = serverBootstrap.bind(port).sync().addListener((future) -> {
            if (future.isSuccess()) {
                System.out.println("port: [" + port + "]绑定成功!");
                return;
            }
            System.out.println("port: [" + port + "]绑定失败!");
        });
        channelFuture.channel().closeFuture().sync();
    }

    public static void main(String[] args) throws InterruptedException {
        FileNettyServer fileNettyServer = new FileNettyServer(9000);
        fileNettyServer.accept();
    }
}
